#include <QSqlDatabase>
#include <QMessageBox>
#include <QDir>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlError>
#include <QtSql/QSqlQuery>
#include <QRegularExpression>

#include "reg_page.h"
#include "ui_reg_page.h"
#include "login.h"
#include "sql_handle.h"

reg_page::reg_page(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::reg_page)
{
    ui->setupUi(this);
}

reg_page::~reg_page()
{
    delete ui;
}

void reg_page::on_back_Button_clicked()
{
    login *s = new login;
    s->show();
    this->close();
}

void reg_page::on_pushButton_3_clicked()
{
    QCoreApplication::exit();
}

void reg_page::on_reg_Button_clicked()
{
    QString username = ui->lineEdit->text().trimmed();
    QString password = ui->lineEdit_2->text().trimmed();

    sql_handle data;
    QSqlDatabase db = data.db;
    QSqlQuery query(db);

    QRegularExpression regex("^[a-zA-Z0-9_]+$");
    QRegularExpressionMatch match = regex.match(username);

    // 检查输入是否为空
    if (username.isEmpty() || password.isEmpty() || (!match.hasMatch()) ) {
        QMessageBox::warning(this, "Input Error", "Username and password cannot be empty! must 0-9 a-z A - Z");
        return;
    }

    query.prepare("INSERT INTO SWIFTCHEN (username, password) VALUES (:username, :password)");
    query.bindValue(":username", username);
    query.bindValue(":password", password);

    if (!query.exec()) {
        QMessageBox::critical(this, "Query Error", "Failed to insert data: " + query.lastError().text());
    } else {
        QMessageBox::information(this, "Success", "Data inserted successfully!");
    }
}

